/******************************************************************************
** 
** Horizontal histogramm.
** 
** File name:	word_lengths_histogramm.c
** Compilation:	cc word_lengths_histogramm.c -o word_lengths_histogramm
** Execution:	./word_lengths_histogramm
** 
** Description:
** Reads the input and prints the horizontal histogramm of word's lengths 
** frequences. "Word" consists of symbols 'a'-'z', 'A'-'Z' and '0'-'9'.
** 
******************************************************************************/
#include <stdio.h>

#define IN 1
#define OUT 0
#define H_MAX_LENGTH 70     // histogramm's string maximum length
#define H_ELEMENT "#"       // element which forms a histogramm line
#define W_MAX_LENGTH 5      // maximum length of the worf treated as separate in the histogramm

int c, i, state, nletters;
int lengths[W_MAX_LENGTH+1]; // lengths[0] is for words that are longer than W_MAX_LENGTH letters
float most_frequent_length;

main()
{
    for (i=0; i<=W_MAX_LENGTH; ++i) {
      lengths[i]=0;
    }
    state = OUT;
    nletters = 0;
    
    // reading the input, counting words' lengths in the lengths[] array
    while ((c=getchar()) != EOF) {
      if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
        if (state == OUT) {
          state = IN;
          nletters=1;
        } else {
          ++nletters;
        }
      } else {
        if (state == IN) {
          state = OUT;
          if (nletters <= W_MAX_LENGTH) {
            ++lengths[nletters];
          } else {
            ++lengths[0];
          }
          nletters = 0;
        }
      }
    }
    
    // defining the most frequent word length
    most_frequent_length = 0;
    for (i=0; i<=W_MAX_LENGTH; ++i) {
      if (most_frequent_length < lengths[i]) {
        most_frequent_length = lengths[i];
      }
    }
    
    // printing the histogramm
    for (i=0; i<=W_MAX_LENGTH; ++i) {
      if (i == 0) {
        printf(">%2d: %4d | ", W_MAX_LENGTH, lengths[0]);
      } else {
        printf("%3d: %4d | ", i, lengths[i]);
      }
      for (nletters=1; nletters<=lengths[i]/most_frequent_length*H_MAX_LENGTH; ++nletters) {
        printf("%s", H_ELEMENT);
      }
      printf("\n");
    }
}

